package com.xuecheng.search.listener;

import com.xuecheng.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MessageListener {
    @Autowired
    private SearchService searchService;
    //更新索引库
    //配置交换机和队列及其绑定关系
    @RabbitListener(
        bindings = @QueueBinding(
                value = @Queue(
                        value = "course.index.queue"
                ),
                exchange = @Exchange(
                        value = "content-exchange",
                        type = ExchangeTypes.TOPIC
                ),
                key = "course.pub"
        )
    )
    public void listener(Long coursePubId) {
        //更新索引
        log.info("获取MQ消息：coursePubId="+coursePubId);
        try {
            searchService.updateIndex(coursePubId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //下架已发布课程，删除索引数据
    //配置交换机和队列及其绑定关系
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = "course.index.queue1"
                    ),
                    exchange = @Exchange(
                            value = "content-exchange",
                            type = ExchangeTypes.TOPIC
                    ),
                    key = "course.offline"
            )
    )
    public void listenerToOffline(Long coursePubId) {
        //更新索引
        log.info("获取MQ消息：coursePubId="+coursePubId);
        try {
            searchService.offlineIndex(coursePubId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
